/* Copyright Andy Mitchell 2007. No warranties */

function Options(gtdinboxPage, el, lightbox, options){
try{
	this._gtdinboxPage = gtdinboxPage;
	this._doc = el.ownerDocument;
	this.el = el;
	this._lightbox = lightbox;
	this._labels = gtdinboxPage._labels;
	this._eventObservers = new EventObservers(this);
	this._options = options || {};
	
	// Attach elements
	this.elClose = this._doc.getElementById("gtd-options-cancel");
	this._eventObservers.observe( this.elClose, "mousedown", this._cancel, true );
	
	this.elSaveClose = this._doc.getElementById("gtd-options-save-close");
	this._eventObservers.observe( this.elSaveClose, "mousedown", this._saveClose, true );
	
	this.elPrefixes = this._doc.getElementById("gtd-options-prefixes");
	this.elPrefixesTable = this.elPrefixes.getElementsByTagName("TABLE")[0];
		this._eventObservers.observe(this.elPrefixesTable, "keyup", this._prefixesEvent, false );
		this._eventObservers.observe(this.elPrefixesTable, "mouseup", this._prefixesEvent, false );
	
	this.elPrefixesMigrate = this._doc.getElementById("gtd-options-migrate");
		this.activePrefixesMigrate(false);
	this.elPrefixesMigrateTable = this.elPrefixesMigrate.getElementsByTagName("TABLE")[0];
	
	this.elStatusContainer = this._doc.getElementById("gtd-options-status");
	
	// Set up defaults
	this._loadOptions();
	this._initPrefixes();
}catch(e){
	if( GTDDEBUGMODE ) alert("Options constructor\n" + e.toString());
}

}

Options.prototype._prefixesEvent = function(event, callback){
	if( this._lastPrefixEvent && !callback ){
		if( ((new Date()).valueOf()-this._lastPrefixEvent)<750 ){
			setTimeout(GIPROTOTYPE.bind(this, function(){this._prefixesEvent(null, true)}), 1000);
			return;
		}
	}
	this._lastPrefixEvent = (new Date()).valueOf();
	
	if( GIPROTOTYPE.element(event).nodeName!="INPUT" ) return;
	this.activePrefixesMigrate( this._prefixes_refreshPreview() );
	this._lastPrefixEvent = null;
};

Options.prototype.activePrefixesMigrate = function(v){
	if( typeof v=="undefined" ) return !(this.elPrefixesMigrate.style.display=="none");
	if( v ){
		this.elPrefixesMigrate.style.display = "";
	}else{
		this.elPrefixesMigrate.style.display = "none";
	}
};

Options.prototype._cancel = function(event){
try{
	if( this._options.postCancel ) this._options.postCancel();
	this._lightbox.active(false);
}catch(e){
	if( GTDDEBUGMODE ) alert("options _cancel\n" + e.toString());
}
};
Options.prototype._saveClose = function(event){
try{
	this.elSaveClose.disabled = true;
	this.elClose.disabled = true;
	
	this.elPrefixSpinner = this._doc.createElement("IMG");
		this.elPrefixSpinner.src = "chrome://gtdinbox/skin/indicator_medium.gif";
	this.elStatusContainer.appendChild( this.elPrefixSpinner );
	
	var els = this.el.getElementsByTagName("*");
	var setting = "";
	for( var i = 0; i < els.length; i++ ){
		if( els[i].nodeName=="INPUT" ) els[i].disabled = true;
		if( setting = els[i].getAttribute("gtdsetting") ){
			if( /labels\.types\..+?\.prefix/.test(els[i].getAttribute("gtdsetting")) ){	// need to correct < >
				els[i].value = els[i].value.replace("<", "&lt;");
				els[i].value = els[i].value.replace(">any ide", "&gt;");
			}
			var settingParts = setting.split(".");
			var settings = this._gtdinboxPage.settings;
			for( var j = 0; j < settingParts.length; j++ ){
				if( j==(settingParts.length-1) ){	// finished
					if( els[i].type.toLowerCase()=="checkbox" ){
						settings[settingParts[j]] = els[i].checked? els[i].checked : null;
					}else{
						settings[settingParts[j]] = els[i].value? els[i].value : null;
					}
				}else{	// create next link
					if( !settings[settingParts[j]] ) settings[settingParts[j]] = {};
					settings = settings[settingParts[j]];
				}
			}
		}
	}
	this._gtdinboxPage.saveSettings();
	

	if( this._options.postSave ) this._options.postSave();
	
	if( this.activePrefixesMigrate()){
		var fCallback = GIPROTOTYPE.bind(this, function(){
			this._lightbox.active(false);
		});
		this._prefixMigrate(null, fCallback)
	}else{
		this._lightbox.active(false);
	}
	
}catch(e){
	if( GTDDEBUGMODE ) alert("options _saveClose\n" + e.toString());
}
};

Options.prototype._loadOptions = function(){
	// Load options for anything with a gtd setting
	var els = this.el.getElementsByTagName("*");
	var setting = "";
	for( var i = 0; i < els.length; i++ ){
		if( setting = els[i].getAttribute("gtdsetting") ){
			var settings = this._gtdinboxPage.settings;
			var settingParts = setting.split(".");
			for( var j = 0; j < settingParts.length; j++ ){
				if( j==(settingParts.length-1) ){	// finished
					if( els[i].type.toLowerCase()=="checkbox" ){
						els[i].checked = settings[settingParts[j]];
					}else{
						els[i].value = settings[settingParts[j]];
					}
				}else{	// create next link
					if( !settings[settingParts[j]] ) break;	// lost settings
					settings = settings[settingParts[j]];
				}
			}
		}
	}
};

Options.prototype._initPrefixes = function(){
try{		
	// Clear old one
	var elTrs = this.elPrefixesTable.getElementsByTagName("TR");
	for( var i = elTrs.length - 1; i >= 0; i-- ){
		if( elTrs[i].getElementsByTagName("INPUT").length==2 ){
			elTrs[i].parentNode.removeChild( elTrs[i] );
		}
	}
	
	
	var foundV1Label = false;
	var settings = this._gtdinboxPage.settings;
	var options = this._gtdinboxPage.gtdinboxBrowser.options;
	var labels = this._labels.getLabelsArray();
	this._prefixCurrentTypes = this._options.prefixCurrentTypes || settings.labels.types;
	this._prefixNewTypes = this._options.prefixNewTypes || settings.labels.types;
	for( l in settings.labels.types ){
		var oldPrefix = this._prefixCurrentTypes[l].prefix;
		var newPrefix = this._prefixNewTypes[l].prefix;
		
		var oldV1Key = l.replace(/s$/, "");
		if( /se$/.test(oldV1Key) ) oldV1Key = oldV1Key.replace(/e$/, "");
		var oldV1Prefix = options.getOption("char", "GTDInbox_Prefix_" + oldV1Key );
		if( !foundV1Label ){
			for( var i = 0; i < labels.length; i++ ){
				if( labels[i].indexOf(oldV1Prefix)==0 && oldV1Prefix!=newPrefix ){
					foundV1Label = true;
					break;
				}
			}
		}
		
		if( newPrefix ){
			var elTr = this._doc.createElement("TR");
				elTr.setAttribute("gtdLabelType", l);
				elTr.setAttribute("gtdCurrentPrefix", oldPrefix);
			this.elPrefixesTable.appendChild(elTr);
			var elTd = this._doc.createElement("TD");
				elTd.setAttribute("valign", "top");
				elTd.innerHTML = l;			// TODO language
			elTr.appendChild( elTd );
			var elTd = this._doc.createElement("TD");
				elTd.setAttribute("valign", "top");
				var elInput = this._doc.createElement("INPUT");
				elInput.setAttribute("gtdsetting", "labels.types." + l + ".prefix");
				elInput.type = "text";
				elInput.value = newPrefix;
				elTd.appendChild( elInput );
			elTr.appendChild( elTd );
		}
	}
	this.activePrefixesMigrate( this._prefixes_refreshPreview() );
	
	if( foundV1Label && !this._options.prefixNewTypes ){
		this.elV1Warning = this._doc.getElementById("gtd-options-v1warning");
		this.elV1Migrate = this._doc.getElementById("gtd-options-v1migrate");
		this.elV1Warning.style.display = "";
		
		this._eventObservers.observe(this.elV1Migrate, "mousedown", GIPROTOTYPE.bind(this, function(){
				try{
					this._migrateAllV1 = true;
					this._prefixes_refreshPreview();
					this.activePrefixesMigrate(true);
				}catch(e){
					if( GTDDEBUGMODE ) alert( "Options v1migrate click\n" + e.toString());
				}
			}), false);
	}
	
	// Show defaults:
	var elDefaults = this._doc.getElementById("gtd-options-defaults");
	for( l in settings.labels.types ){
		var elDefault = this._doc.createElement("DIV");
			elDefault.innerHTML = l;
			elDefault.className = "default-labels-box";
		var foundDefault = false;
		var elTableDefaults = this._doc.createElement("TABLE");
		for( d in settings.labels.types[l].defaults ){
			foundDefault = true;
			var elTrDefault = this._doc.createElement("TR");
				var elTdDefault = this._doc.createElement("TD");
				elTdDefault.innerHTML = d;
				elTrDefault.appendChild( elTdDefault );
				var elTdDefault = this._doc.createElement("TD");
					var elInput = this._doc.createElement("INPUT");
					elInput.setAttribute("gtdsetting", "labels.types." + l + ".defaults." + d);
					elInput.type = "text";
					elInput.value = settings.labels.types[l].defaults[d];
					elTdDefault.appendChild( elInput );
				elTrDefault.appendChild( elTdDefault );
			elTableDefaults.appendChild( elTrDefault );
		}
		elDefault.appendChild( elTableDefaults );	
		if( foundDefault ) elDefaults.appendChild( elDefault );
	}
	
}catch(e){
	if( GTDDEBUGMODE ) alert("Lightbox _showMigrate\n" + e.toString());
}
};
Options.prototype._prefixes_refreshPreview = function(event){
try{
	// Update all labels, using new prefixes
	
	
	var settings = this._gtdinboxPage.settings;
	var labels = GIPROTOTYPE.clone(this._labels.getLabelsArray());
	
	
	// Clear old one
	var elTrs = this.elPrefixesMigrateTable.getElementsByTagName("TR");
	for( var i = elTrs.length - 1; i >= 0; i-- ){
		if( elTrs[i].getElementsByTagName("INPUT").length==2 ){
			elTrs[i].parentNode.removeChild( elTrs[i] );
		}
	}
	
	var processedLabels = {};
	var fCreateRow = GIPROTOTYPE.bind(this, function(labelType, oldPrefix, newPrefix, oldLabel ){
			if( processedLabels[oldLabel] ) return;
			processedLabels[oldLabel] = true;
			
			var newLabel = oldLabel.replace(oldPrefix, newPrefix);
			if( l=="Old" ){	// can be old:p:
				for( l2 in this._currentTypes ){
					newLabel = newLabel.replace(this._currentTypes[l2].prefix, settings.labels.types[l2].prefix);
				}
			}
	
			var elTr = this._doc.createElement("TR");
				elTr.setAttribute("gtdLabelType", labelType);
				elTr.setAttribute("gtdNewPrefix", newPrefix);
			this.elPrefixesMigrateTable.appendChild(elTr);
			var elTd = this._doc.createElement("TD");
				var elInput = this._doc.createElement("INPUT");
				elInput.type = "text";
				elInput.value = oldLabel;
				elTd.appendChild( elInput );
			elTr.appendChild( elTd );
			var elTd = this._doc.createElement("TD");
				var elInput = this._doc.createElement("INPUT");
				elInput.type = "text";
				elInput.value = newLabel;
				elTd.appendChild( elInput );
			elTr.appendChild( elTd );
	});
	
	// Create new ones
	var prefixNewTypes = {};
	var count = 0;
	var elTrs = this.elPrefixesTable.getElementsByTagName("TR");
	for( var i = 0; i < elTrs.length; i++ ){
		var l = elTrs[i].getAttribute("gtdLabelType");
		var elInputs = elTrs[i].getElementsByTagName("INPUT");
		if( elInputs.length==1 ){
			var oldPrefix = elTrs[i].getAttribute("gtdCurrentPrefix");
			var newPrefix = elInputs[0].value;
			prefixNewTypes[l] = {'prefix': newPrefix};
			
			if( oldPrefix!=newPrefix ){
				for( var j = labels.length -1; j >= 0; j-- ){
					if( labels[j].indexOf( oldPrefix )==0 ){
						count++;
						fCreateRow( l, oldPrefix, newPrefix, labels[j]);						
						labels.splice(j, 1);
					}
				}
			}
		}
	}
	
	
	if( this._migrateAllV1 ){	// Move all labels with a V1
		var labels = this._labels.getLabelsArray();
		var settings = this._gtdinboxPage.settings;
		var options = this._gtdinboxPage.gtdinboxBrowser.options;
		for( l in settings.labels.types ){
			if( prefixNewTypes[l] ){
				var oldKey = l.replace(/s$/, "");
				if( /se$/.test(oldKey) ) oldKey = oldKey.replace(/e$/, "");
				var oldPrefix = options.getOption("char", "GTDInbox_Prefix_" + oldKey );
				var newPrefix = prefixNewTypes[l].prefix;
				if( oldPrefix!=newPrefix ){
					for( var i = 0; i < labels.length; i++ ){
						if( labels[i].indexOf(oldPrefix)==0 ){	// Old Prefix matches
							fCreateRow(l, oldPrefix, newPrefix, labels[i]);
						}
					}
				}
			}
		}
	}
	
	if( count==0 ){	// nothing changed
		//this._activePrefixMigrateComplete(true);
		return false;
	}else{
		//this._activePrefixMigrateComplete(false);
		return true;
	}
}catch(e){
	if( GTDDEBUGMODE ) alert("Options _prefixes_refreshPreview\n" + e.toString());
}
};

Options.prototype._prefixMigrate = function(event, _callback){
try{
	
	var elTrs = this.elPrefixesMigrateTable.getElementsByTagName("TR");
	var replacements = [];
	
	var finalCallback = GIPROTOTYPE.bind(this, function(){
		try{
		
		
		this._gtdinboxPage.saveSettings();
		if( this._options.postMigrate ) this._options.postMigrate();
		
		var el = this._gtdinboxPage.gmailDOM.element("inbox-link");
		if( el ) GIPROTOTYPE.doMouseEvent(this._doc, el, "click");	// refresh
		
		if( _callback ) _callback();
		
		}catch(e){
			if( GTDDEBUGMODE ) alert("_prefixMigrate finalCallback\n" + e.toString());
		}
	});
	
	
	var count = {i:0};
	for( var i = elTrs.length - 1; i >= 0; i-- ){
		var elInputs = elTrs[i].getElementsByTagName("INPUT");
		if( elInputs.length==2 && elInputs[0].value && elInputs[1].value){
			var newPrefix = elTrs[i].getAttribute("gtdNewPrefix");
			var key = elTrs[i].getAttribute("gtdLabelType");
			var oldKey = key.replace(/s$/, "");
			if( /se$/.test(oldKey) ) oldKey = oldKey.replace(/e$/, "");
			
			var elTr = elTrs[i];
			
			var callback = function(){
					try{
					//if( elTr.parentNode ) elTr.parentNode.removeChild(elTr);
					if( this._gtdinboxPage.settings.labels.types[key] ){
						this._gtdinboxPage.settings.labels.types[key].prefix = newPrefix;
					}
					if( --count.i==0 ){
						if( finalCallback ) finalCallback();
					}
					
					}catch(e){
						if( GTDDEBUGMODE ) alert("_prefixMigrate callback\n" + e.toString());
					}
				};
			count.i++;
			this._gtdinboxPage.gmailDOM.renameLabel([elInputs[0].value, elInputs[1].value], GIPROTOTYPE.bind(this,callback));

		}
	}

	if( count.i>0 ){
		return true;
	}else{
		if( _callback ) _callback();
	}
	
}catch(e){
	if( GTDDEBUGMODE ) alert("lightbox migrate\n" + e.toString());
}
};

/*
Options.prototype._activePrefixMigrateComplete = function(v){
try{
	if( v ){
		if( !this.elImgTick ){
			this.elImgTick = this._doc.createElement("IMG");
			this.elImgTick.src = "chrome://gtdinbox/content/tick.png";
			this.elMigrate.parentNode.insertBefore(this.elImgTick, this.elMigrate);
		}
		this.elImgTick.style.display = "";
		this.elMigrate.disabled = true;
	}else{
		if( this.elImgTick ) this.elImgTick.style.display = "none";
		this.elMigrate.disabled = false;
	}
}catch(e){
	alert("Options activePrefixMigrateComplete\n" + e.toString());
}
};
*/